/**
 * Copyright (C), 2015-2024, XXX有限公司
 * FileName: MySingleLinkedList
 * Author:   Administrator
 * Date:     2024/3/24 11:39
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Administrator
 * @create 2024/3/24
 * @since 1.0.0
 */
public class MySingleLinkedList<T> {

    private Node head;

    private int size;


    public MySingleLinkedList() {
        this.head = new Node<T>(null, null);
        this.size = 0;
    }

    public int size() {
        return size;
    }

    public T get(int pos) {
        Node<T> node = this.getNode(pos);
        if (node == null) {
            return null;
        }
        return node.data;
    }


    public void reverse() {
        // 获取正序链表的第一个元素
        Node<T> first = this.head.next;
        Node<T> reverseHead = new Node<T>(null, null);
        first.next = reverseHead.next;

        while (first != null) {
            //原有的头节点执行first的下一个节点
            this.head.next = first.next;
            first.next = reverseHead.next;
            reverseHead.next = first;
            first = this.head.next;
        }
    }

    private Node<T> getNode(int pos) {
        if (pos == -1) {
            return this.head;
        }
        Node<T> target = this.head.next;
        //获取指定位置的元素
        for (int i = 0; i < pos; i++) {
            target = target.next;
        }
        return target;
    }

    public void add(T data) {
        Node<T> node = new Node<T>(data, null);
        if (this.size == 0) {
            this.head.next = node;
            this.size++;
            return;
        }
        Node<T> last = this.getNode(this.size - 1);
        last.next = node;
        // 累计的数字加1
        this.size++;
    }


    public void add(T data, int pos) {
        Node<T> node = new Node<T>(data, null);
        Node<T> cur = this.getNode(pos);
        Node<T> before = this.getNode(pos - 1);
        node.next = cur;
        before.next = node;
        this.size++;
    }


    private class Node<T> {

        private T data;
        private Node<T> next;


        public Node(T data, Node<T> next) {
            this.next = next;
            this.data = data;
        }
    }
}